import {
	createRouter,
	createWebHashHistory
} from 'vue-router'
import routes from './routes'
import store from '@/store'
import config from '@/config'
import {getToken,removeToken} from '@/utils/token'
import {checkAccess} from '@/utils'

const router = createRouter({
	history: createWebHashHistory(),
	routes
})
var views = routes.find(item => item.name == "Home")
var mainstack=views ? views.children : []
var all=mainstack.map(item=>{
	var newItem={
		label:item.meta.title,
		url:item.path,
		name:item.name,
		children:[]
	}
	if(item.children&&item.children.length>0){
		newItem.children=item.children.map(child=>{
			var newChild={
				label:child.meta.title,
				url:child.path,
				name:child.name,
			}
			return newChild
		})
	}
	return newItem
})
console.log(JSON.stringify(all));

router.beforeEach((to,from,next)=>{
	let token=getToken()
	if(to.name!=config.loginRouteName){
		if(token){
			var user=store.state.app.user
			if(!user){
				removeToken()
				next({name:config.loginRouteName})
			}else if(checkAccess(to,user)){
				store.commit('addTab',to)
				next()
			}else{
				next('/403')
			}

		}else{
			next({name:config.loginRouteName})
		}
	}else{
		if(token){
			next({name:config.baseRouteName})
		}else{
			next()
		}
	}
})

export default router
